package main

import (
	"log"
	"net/http"
	"text/template"
	"time"
)

type User struct {
	Id        int
	Name      string
	Title     string
	CreatedAt time.Time
}

type Class struct {
	Name     string
	Total    int
	Students []User
}

func main() {
	const templa = `  <div>
    <p>
      <span>班级: {{.Name}} </span>
      <span>学生 {{.Total}} 总数</span>
    </p>
    <table>
      <thead>
        <td>编号</td>
        <td>姓名</td>
        <td>职位</td>
        <td>生日</td>
      </thead>
	{{range .Students}}
      <tr>
        <td>{{.Id}}</td>
        <td>{{.Name}}</td>
        <td>{{.Title | printf "%.64s"}}</td>
        <td>{{.CreatedAt | daysAgo}}</td>
      </tr>
	{{end}}
    </table>
  </div>`

	var report = template.Must(template.New("classlist").
		Funcs(template.FuncMap{"daysAgo": daysAgo}).
		Parse(templa))

	students := []User{
		{
			Id:        1,
			Name:      "张三",
			Title:     "班长",
			CreatedAt: time.Date(2001, 1, 2, 0, 0, 0, 0, time.Local),
		},
		{
			Id:        2,
			Name:      "李四",
			Title:     "学习委员",
			CreatedAt: time.Date(2000, 11, 25, 0, 0, 0, 0, time.Local),
		},
		{
			Id:        3,
			Name:      "王五",
			Title:     "组长",
			CreatedAt: time.Date(2000, 8, 16, 0, 0, 0, 0, time.Local),
		},
	}
	result := Class{
		Name:     "三年级一班",
		Total:    len(students),
		Students: students,
	}
	http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		if err := report.Execute(w, result); err != nil {
			log.Fatal(err)
		}
	})
	log.Fatal(http.ListenAndServe("localhost:8000", nil))

}

func daysAgo(t time.Time) string {
	return t.Format("2006-01-02")
}
